var express = require('express');
var router = express.Router();
var { jjkModel, MyOrderModel, ExpressOrderModel, TakeoutOrderModel } = require('../db/jjk');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('JJK API is working!');
});

// 测试路由
router.get('/test', function(req, res, next) {
  res.json({
    success: true,
    message: 'JJK API test successful',
    timestamp: new Date()
  });
});

// ========== 我的接单相关路由 ==========

// 获取用户的所有接单记录
router.get('/myOrders/user/:userId', async function(req, res, next) {
    try {
        const userId = req.params.userId;
        const status = req.query.status; // 可选的状态过滤
        
        let query = { userId: userId };
        if (status && status !== 'all') {
            query.status = status;
        }
        
        const orders = await MyOrderModel.find(query).sort({ acceptTime: -1 });
        
        res.json({
            success: true,
            data: orders,
            message: '获取订单列表成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取订单列表失败',
            error: error.message
        });
    }
});

// 添加新的接单记录（抢单成功后调用）
router.post('/myOrders/add', async function(req, res, next) {
    try {
        const {
            orderId,
            userId,
            title,
            pickup,
            delivery,
            price,
            serviceType,
            originalOrder
        } = req.body;
        
        console.log('接收到的抢单数据:', req.body);
        
        // 数据验证和格式统一
        const validatedData = {
            orderId: String(orderId || ''), // 确保是字符串类型，与数据库一致
            userId: String(userId || ''), // 确保是字符串类型
            title: String(title || ''), // 确保是字符串类型
            pickup: String(pickup || ''), // 确保是字符串类型
            delivery: String(delivery || ''), // 确保是字符串类型
            price: String(price || '0.00'), // 确保是字符串类型
            serviceType: serviceType && ['express', 'takeout'].includes(serviceType) ? serviceType : 'express', // 验证枚举值
            status: 'ongoing',
            originalOrder: originalOrder || {}
        };
        
        console.log('验证后的数据:', validatedData);
        
        // 基础数据验证
        if (!validatedData.orderId) {
            return res.status(400).json({
                success: false,
                message: '订单ID不能为空'
            });
        }
        
        if (!validatedData.userId) {
            return res.status(400).json({
                success: false,
                message: '用户ID不能为空'
            });
        }
        
        if (!validatedData.title) {
            return res.status(400).json({
                success: false,
                message: '订单标题不能为空'
            });
        }
        
        // 检查订单是否已存在
        const existingOrder = await MyOrderModel.findOne({ orderId: validatedData.orderId });
        if (existingOrder) {
            return res.status(400).json({
                success: false,
                message: '订单已存在，请勿重复抢单'
            });
        }
        
        console.log('准备保存的数据:', validatedData);
        
        const newOrder = new MyOrderModel(validatedData);
        const savedOrder = await newOrder.save();
        
        console.log('保存成功:', savedOrder);
        
        res.json({
            success: true,
            data: savedOrder,
            message: '抢单成功'
        });
    } catch (error) {
        console.error('抢单失败详细错误:', error);
        console.error('错误堆栈:', error.stack);
        
        // 根据不同错误类型返回不同信息
        let errorMessage = '抢单失败';
        if (error.code === 11000) {
            errorMessage = '订单已存在，请勿重复抢单';
        } else if (error.name === 'ValidationError') {
            errorMessage = '数据验证失败: ' + error.message;
        } else if (error.name === 'CastError') {
            errorMessage = '数据类型错误: ' + error.message;
        }
        
        res.status(500).json({
            success: false,
            message: errorMessage,
            error: error.message,
            details: process.env.NODE_ENV === 'development' ? error.stack : undefined
        });
    }
});

// 完成订单
router.put('/myOrders/complete/:orderId', async function(req, res, next) {
    try {
        const orderId = req.params.orderId;
        const userId = req.body.userId;
        
        const updatedOrder = await MyOrderModel.findOneAndUpdate(
            { orderId: orderId, userId: userId },
            { 
                status: 'completed',
                completeTime: new Date()
            },
            { new: true }
        );
        
        if (!updatedOrder) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }
        
        res.json({
            success: true,
            data: updatedOrder,
            message: '订单完成成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '订单完成失败',
            error: error.message
        });
    }
});

// 获取订单统计信息
router.get('/myOrders/stats/:userId', async function(req, res, next) {
    try {
        const userId = req.params.userId;
        
        const totalCount = await MyOrderModel.countDocuments({ userId: userId });
        const ongoingCount = await MyOrderModel.countDocuments({ userId: userId, status: 'ongoing' });
        const completedCount = await MyOrderModel.countDocuments({ userId: userId, status: 'completed' });
        
        res.json({
            success: true,
            data: {
                total: totalCount,
                ongoing: ongoingCount,
                completed: completedCount
            },
            message: '获取统计信息成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取统计信息失败',
            error: error.message
        });
    }
});

// 删除订单（可选功能）
router.delete('/myOrders/delete/:orderId', async function(req, res, next) {
    try {
        const orderId = req.params.orderId;
        const userId = req.body.userId;
        
        const deletedOrder = await MyOrderModel.findOneAndDelete({
            orderId: orderId,
            userId: userId
        });
        
        if (!deletedOrder) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }
        
        res.json({
            success: true,
            message: '订单删除成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '订单删除失败',
            error: error.message
        });
    }
});

// ========== 快递代取订单相关路由 ==========

// 创建快递代取订单
router.post('/express/create', async function(req, res, next) {
    try {
        const {
            userId,
            deliveryLocation,
            deliveryTime,
            baseFee,
            tipAmount,
            totalPrice,
            hasMoreRequirements,
            specialNote
        } = req.body;
        
        // 生成订单ID
        const orderId = 'EXP' + Date.now();
        
        const orderData = {
            orderId,
            userId,
            deliveryLocation,
            deliveryTime,
            baseFee: baseFee || 5,
            tipAmount: tipAmount || 0,
            totalPrice,
            hasMoreRequirements: hasMoreRequirements || false,
            specialNote: specialNote || '',
            status: 'pending'
        };
        
        const newOrder = new ExpressOrderModel(orderData);
        const savedOrder = await newOrder.save();
        
        res.json({
            success: true,
            data: savedOrder,
            message: '快递代取订单创建成功'
        });
    } catch (error) {
        console.error('创建快递代取订单失败:', error);
        res.status(500).json({
            success: false,
            message: '创建订单失败',
            error: error.message
        });
    }
});

// 获取用户的快递代取订单
router.get('/express/user/:userId', async function(req, res, next) {
    try {
        const userId = req.params.userId;
        const status = req.query.status;
        
        let query = { userId: userId };
        if (status && status !== 'all') {
            query.status = status;
        }
        
        const orders = await ExpressOrderModel.find(query).sort({ orderTime: -1 });
        
        res.json({
            success: true,
            data: orders,
            message: '获取快递代取订单成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取订单失败',
            error: error.message
        });
    }
});

// 更新快递代取订单状态
router.put('/express/status/:orderId', async function(req, res, next) {
    try {
        const orderId = req.params.orderId;
        const { status, userId } = req.body;
        
        const updateData = { status };
        if (status === 'completed') {
            updateData.completeTime = new Date();
        } else if (status === 'accepted') {
            updateData.acceptTime = new Date();
        }
        
        const updatedOrder = await ExpressOrderModel.findOneAndUpdate(
            { orderId: orderId, userId: userId },
            updateData,
            { new: true }
        );
        
        if (!updatedOrder) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }
        
        res.json({
            success: true,
            data: updatedOrder,
            message: '订单状态更新成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '更新订单状态失败',
            error: error.message
        });
    }
});

// ========== 帮拿外卖订单相关路由 ==========

// 创建帮拿外卖订单
router.post('/takeout/create', async function(req, res, next) {
    try {
        const {
            userId,
            selectedTime,
            orderDetail,
            basePrice,
            tipAmount,
            totalAmount
        } = req.body;
        
        // 生成订单ID
        const orderId = 'TAK' + Date.now();
        
        const orderData = {
            orderId,
            userId,
            selectedTime,
            orderDetail,
            basePrice: basePrice || 3,
            tipAmount: tipAmount || 3,
            totalAmount,
            status: 'pending'
        };
        
        const newOrder = new TakeoutOrderModel(orderData);
        const savedOrder = await newOrder.save();
        
        res.json({
            success: true,
            data: savedOrder,
            message: '帮拿外卖订单创建成功'
        });
    } catch (error) {
        console.error('创建帮拿外卖订单失败:', error);
        res.status(500).json({
            success: false,
            message: '创建订单失败',
            error: error.message
        });
    }
});

// 获取用户的帮拿外卖订单
router.get('/takeout/user/:userId', async function(req, res, next) {
    try {
        const userId = req.params.userId;
        const status = req.query.status;
        
        let query = { userId: userId };
        if (status && status !== 'all') {
            query.status = status;
        }
        
        const orders = await TakeoutOrderModel.find(query).sort({ orderTime: -1 });
        
        res.json({
            success: true,
            data: orders,
            message: '获取帮拿外卖订单成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取订单失败',
            error: error.message
        });
    }
});

// 更新帮拿外卖订单状态
router.put('/takeout/status/:orderId', async function(req, res, next) {
    try {
        const orderId = req.params.orderId;
        const { status, userId } = req.body;
        
        const updateData = { status };
        if (status === 'completed') {
            updateData.completeTime = new Date();
        } else if (status === 'accepted') {
            updateData.acceptTime = new Date();
        }
        
        const updatedOrder = await TakeoutOrderModel.findOneAndUpdate(
            { orderId: orderId, userId: userId },
            updateData,
            { new: true }
        );
        
        if (!updatedOrder) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }
        
        res.json({
            success: true,
            data: updatedOrder,
            message: '订单状态更新成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '更新订单状态失败',
            error: error.message
        });
    }
});

// ========== 统一订单查询接口 ==========

// 获取用户所有类型的订单
router.get('/orders/user/:userId', async function(req, res, next) {
    try {
        const userId = req.params.userId;
        const serviceType = req.query.serviceType; // 'express', 'takeout', 'all'
        
        let allOrders = [];
        
        if (!serviceType || serviceType === 'all' || serviceType === 'express') {
            const expressOrders = await ExpressOrderModel.find({ userId }).sort({ orderTime: -1 });
            const formattedExpressOrders = expressOrders.map(order => ({
                ...order.toObject(),
                serviceType: 'express',
                serviceTypeName: '快递代取'
            }));
            allOrders = allOrders.concat(formattedExpressOrders);
        }
        
        if (!serviceType || serviceType === 'all' || serviceType === 'takeout') {
            const takeoutOrders = await TakeoutOrderModel.find({ userId }).sort({ orderTime: -1 });
            const formattedTakeoutOrders = takeoutOrders.map(order => ({
                ...order.toObject(),
                serviceType: 'takeout',
                serviceTypeName: '帮拿外卖'
            }));
            allOrders = allOrders.concat(formattedTakeoutOrders);
        }
        
        // 按时间排序
        allOrders.sort((a, b) => new Date(b.orderTime) - new Date(a.orderTime));
        
        res.json({
            success: true,
            data: allOrders,
            message: '获取订单列表成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取订单失败',
            error: error.message
        });
    }
});

module.exports = router;
